package com.weizhu.swufer.core.rpc;

import com.google.common.util.concurrent.ListenableFuture;
import com.weizhu.swufer.grpc.Response;

import java.util.HashMap;
import java.util.Map;

public class RpcContext  {

    private Map<String,Object> contextParameters;

    private ListenableFuture<?> listenableFuture;

    public Map<String, Object> getContextParameters() {
        return contextParameters;
    }

    public Object getParameter(String key){
        return contextParameters.get(key);
    }

    public void setParameter(String key,Object value){
        if (contextParameters == null){
            contextParameters = new HashMap<>();
        }
        contextParameters.put(key,value);
    }

    public void setContextParameters(Map<String, Object> contextParameters) {
        this.contextParameters = contextParameters;
    }

    private static final ThreadLocal<RpcContext> rpcContextThreadLocal = ThreadLocal.withInitial(() -> {
        RpcContext context= new RpcContext();
        context.setContextParameters(new HashMap<>());
        return context;
    });

    public static RpcContext getContext() {
        return rpcContextThreadLocal.get();
    }

    public static void removeContext() {
        rpcContextThreadLocal.remove();
    }

    private RpcContext() {
    }


    @SuppressWarnings("unchecked")
    public <T> ListenableFuture<T> getListenableFuture() {
        return (ListenableFuture<T>) listenableFuture;
    }

    public void setListenableFuture(ListenableFuture<?> listenableFuture) {
        this.listenableFuture = listenableFuture;
    }
}